<template>
  <el-form :model="form" ref="formRef" status-icon>
    <el-form-item label="用户名" prop="username" :rules="[{ required: true, message: '请输入用户名', trigger: 'blur' }]">
      <el-input v-model="form.username" />
    </el-form-item>
    <el-form-item label="密码" prop="password" :rules="[{ required: true, message: '请输入密码', trigger: 'blur' }]">
      <el-input type="password" v-model="form.password" />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="handleLogin">登录</el-button>
    </el-form-item>
  </el-form>
</template>

<script>
import { login } from '@/api/api';
import { ref } from 'vue';
import { useRouter } from 'vue-router';

export default {
  setup() {
    const router = useRouter();
    const form = ref({
      username: '',
      password: '',
    });

    const handleLogin = async () => {
      try {
        const response = await login(form.value);
        if (response.data.code === 200) {
          localStorage.setItem('token', response.data.data.token);
          router.push({ name: 'Home' });
        } else {
          alert('登录失败');
        }
      } catch (error) {
        alert('登录出错');
      }
    };

    return {
      form,
      handleLogin,
    };
  },
};
</script>
